package cn.jason.lock;

import cn.jason.domain.ResourceLock;
import cn.jason.mapper.ResourceLockMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @Author: Jason
 * @Date: 2022/9/19 18:53
 */
@Component
public class DbLockX implements ItsourceLock {

    @Autowired
    private ResourceLockMapper mapper;
    //goods_id  order_id
    @Transactional
    @Override
    public void lock(String resourceName) {
        if (tryLock(resourceName))
            return;

        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        lock(resourceName);

    }

    @Transactional
    @Override
    public void unlock(String resourceName) {
        mapper.removeByResourceName(resourceName);
    }

    @Override
    public boolean tryLock(String resourceName) {
        //select * from resource_lock where resource_name = #{resourceName} for update
        ResourceLock resourceLock = mapper.loadByResourceName(resourceName);
        if (resourceLock==null){
            ResourceLock resourceLock1 = new ResourceLock();
            resourceLock1.setResource_name(resourceName);
            resourceLock1.setDesc("xxx");
            resourceLock1.setOwner("yphtest");
            resourceLock1.setUpdate_time(new Date());
            //insert into resource_lock(resource_name,owner,desc,update_time) values(#{resource_name},#{owner},#{desc},#{update_time})
            mapper.save(resourceLock1);
            return true;
        }
        return false;
    }
}
